<?
/**
 * BulkAddFixedPriceItemRequest
 * @todo Also allow the siteid and version to be altered.
 * @todo Add in error reporting
 * @todo Fix up Listing Duration code
 * 
 */
class BulkAddFixedPriceItemRequest extends gravy{

	public $headerIndex;
	public $headerMap;
	public $template;
	public $data;
	public $outputFile;
	public $outputData;
	public $uploadFile;
	public $streamHandler;
	public $itemCount=0;

	public function __construct(){
		parent::__construct();
	}

	public function getHeaderMap(){
		return($this->headerMap);
	}
	public function setHeaderMap($headerMap){
		$this->headerMap=$headerMap;
	}

	public function getItemCount(){
		return($this->itemCount);
	}

	public function getHeaderIndex(){
		return($this->headerIndex);
	}
	public function setHeaderIndex($headerIndex){
		$this->headerIndex=$headerIndex;
	}

	public function getOutputFile(){
		return($this->outputFile);
	}
	public function setOutputFile($outputFile){
		$this->outputFile=$outputFile;
	}

	public function loadTemplate($templateFile){
		$result=false;
		if(file_exists($templateFile)){
			$result=($this->template=@file_get_contents($templateFile));
		}else{
			$this->debug("Template File Does NOT exist.",$templateFile);
		}
		return($result);
	}

	public function initializePayload(){
		$result=false;
		$this->itemCount=0;
		if(($this->streamHandler=@gzopen($this->getOutputFile(),'w9'))){
			$output="<?xml version=\"1.0\" encoding=\"UTF-8\" ?>
<BulkDataExchangeRequests>
	<Header>
		<SiteID>15</SiteID>
		<Version>663</Version>
	</Header>
";
			$result=((@fwrite($this->streamHandler,$output))===TRUE);
		}else{
			$this->debug("Error Opening Output File",$this->getOutputFile());
		}
		return($result);
	}

	public function getMappedData($item){
		$result=false;
		if(is_array($item)&&count($item)>0){
			$result=array();
			for($c=0;$c<count($item);$c++){
				if($this->headerIndex[$c]["field"]!="SellerTag"&&$this->headerIndex[$c]["field"]!="IgnoreField"){
					$result[$this->headerIndex[$c]["field"]]=$item[$c];
				}
			}
		}
		return($result);
	}

	public function getSellerTags($item){
		$result=false;
		if(is_array($item)&&count($item)>0){
			$result=array();
			for($c=0;$c<count($item);$c++){
				if($this->headerIndex[$c]["field"]=="SellerTag"){
					if(strlen($this->headerIndex[$c]["value"])>0&&strlen($item[$c])>0){
						$result[$this->headerIndex[$c]["value"]]=$item[$c];
					}
				}
			}
		}
		return($result);
	}

	public function getMergedDescription($item){
		$result=$this->template;
		/**
		 * Listing Data
		 */
		if(is_array($item)&&count($item)>0){
			for($c=0;$c<count($item);$c++){
				$result=str_replace("@@".strtoupper($this->headerIndex[$c]["value"])."@@",$item[$c],$result);
				$result=str_replace("@@".str_replace(" ","_",strtoupper($this->headerIndex[$c]["value"]))."@@",$item[$c],$result);
				$result=str_replace("@@".$this->headerIndex[$c]["value"]."@@",$item[$c],$result);
				$result=str_replace("@@".str_replace(" ","_",$this->headerIndex[$c]["value"])."@@",$item[$c],$result);

				$result=str_replace("@@".$this->headerIndex[$c]["field"]."@@",$item[$c],$result);
				$result=str_replace("@@".strtoupper($this->headerIndex[$c]["field"])."@@",$item[$c],$result);
			}
		}
		/**
		 * Seller Tags Table
		 */
		$tags=$this->getSellerTags($item);
		$list="";
		if(is_array($tags)&&count($tags)>0){
			$list.="<ul>";
			foreach($tags as $name=>$value){
				$list.="<li><span>$name:</span> $value</li>";
			}
			$list.="</ul>";
			$result=str_replace("@@ITEM_SPECIFICS_TABLE@@",$list,$result);
		}
		return($result);
	}

	public function addPayloadItem($item){
		$result=false;
			//Error<ScheduleTime>".gmdate("Y-m-d\TH:i:s.000\Z",time()+36400)."</ScheduleTime>
		$this->itemCount++;
		$row=$this->getMappedData($item);
		$tags=$this->getSellerTags($item);
		$description=$this->getMergedDescription($item);
		$output="	<AddItemRequest xmlns=\"urn:ebay:apis:eBLBaseComponents\">
		<ErrorLanguage>en_US</ErrorLanguage>
		<WarningLevel>High</WarningLevel>
		<Version>663</Version>
		<MessageID>".$row["SKU"]."</MessageID>
		<Item>
			<AutoPay>true</AutoPay>
			<BuyItNowPrice currencyID=\"AUD\">0.0</BuyItNowPrice>
			<Country>AU</Country>
			<Currency>AUD</Currency>
";
		$output.="			<Description><![CDATA[".$description."]]></Description>
";
		$output.="			<HitCounter>HiddenStyle</HitCounter>
";
		$output.="			<ListingDuration>GTC</ListingDuration>
";
		$output.="			<ListingType>FixedPriceItem</ListingType>
";
		$output.="			<Location>Australia</Location>
";
		$output.="			<PaymentMethods>PayPal</PaymentMethods>
";
		$output.="			<PaymentMethods>MoneyXferAccepted</PaymentMethods>
";
		$output.="			<PayPalEmailAddress>support@treeet.com.au</PayPalEmailAddress>
";
		$output.="			<PrimaryCategory>
								<CategoryID>".$row["PrimaryCategoryID"]."</CategoryID>
							</PrimaryCategory>
";
		$output.="			<Quantity>".$row["Quantity"]."</Quantity>
";
		$output.="			<ShippingDetails>
					<ShippingServiceOptions>
						<ShippingService>AU_Regular</ShippingService>
						<ShippingServiceCost currencyID=\"AUD\">0.0</ShippingServiceCost>
						<ShippingServiceAdditionalCost currencyID=\"AUD\">0.0</ShippingServiceAdditionalCost>
						<ShippingServicePriority>1</ShippingServicePriority>
						<ExpeditedService>false</ExpeditedService>
						<FreeShipping>true</FreeShipping>
					</ShippingServiceOptions>
					<InternationalShippingServiceOption>
						<ShippingService>AU_OtherInternational</ShippingService>
						<ShippingServiceCost currencyID=\"AUD\">6.5</ShippingServiceCost>
						<ShippingServiceAdditionalCost currencyID=\"AUD\">0.0</ShippingServiceAdditionalCost>
						<ShippingServicePriority>2</ShippingServicePriority>
						<ShipToLocation>NZ</ShipToLocation>
					</InternationalShippingServiceOption>
					<ShippingType>Flat</ShippingType>
			    </ShippingDetails>
";
		$output.="			<StartPrice currencyID=\"AUD\">".preg_replace("/[^0-9\.]/","",$row["StartPrice"])."</StartPrice>
";
		$output.="			<Storefront>
					<StoreCategoryID>".$row["StoreCategoryID"]."</StoreCategoryID>
					<StoreCategory2ID>0</StoreCategory2ID>
				</Storefront>
";
		$output.="			<Title><![CDATA[".$row["Title"]."]]></Title>
";
		$output.="			<SKU>".$row["SKU"]."</SKU>
";
		$output.="			<PictureDetails>
					<GalleryType>Gallery</GalleryType>
					<GalleryURL>".$row["PictureURL"]."</GalleryURL>
					<PictureURL>".$row["PictureURL"]."</PictureURL>
				</PictureDetails>
";
		$output.="			<DispatchTimeMax>".$row["DispatchTimeMax"]."</DispatchTimeMax>
";

		if(is_array($tags)&&count($tags)>0){
			$output.="			<ItemSpecifics>
";
			foreach($tags as $name=>$value){
				$output.="			<NameValueList>
				<Name>".htmlentities($name)."</Name>
				<Value>".htmlentities($value)."</Value>
			</NameValueList>
";
			}
			$output.="			</ItemSpecifics>
";
		}

		$output.="			<ReturnPolicy>
					<RefundOption>MoneyBack</RefundOption>
					<ReturnsWithinOption>Days_".$row["ReturnsWithinOption"]."</ReturnsWithinOption>
					<ReturnsAcceptedOption>ReturnsAccepted</ReturnsAcceptedOption>
					<Description>".$row["ReturnPolicyDescription"]."</Description>
					<ShippingCostPaidByOption>Seller</ShippingCostPaidByOption>
				</ReturnPolicy>
				<ConditionID>1000</ConditionID>
				<ConditionDisplayName>Brand New</ConditionDisplayName>
";

		$output.="		</Item>
		</AddItemRequest>
";
		$result=$this->buffer($output);
		return($result);
	}

	public function buffer($text=""){
		$this->outputData.=$text;
		return(true);
	}

	public function getOuput(){
		return($this->outputData);
	}

	public function getFileSize(){
		$this->debug("FileSize",filesize($this->getOutputFile()));
		return(filesize($this->getOutputFile()));
	}

	public function flush(){
		if(((@gzwrite($this->streamHandler,$this->outputData))===TRUE)){
			$result=false;
		}
		$this->outputData="";
		return($result);
	}

	public function finalizePayload(){
		return($this->buffer("</BulkDataExchangeRequests>"));
	}

	public function close(){
		$this->flush();
		$result=@gzclose($this->streamHandler);
		return($result);
	}

}
?>